package com.penghaisoft.microwms.materialhand.web.outwarehouse.controller;

import com.penghaisoft.microwms.common.Constant;
import com.penghaisoft.microwms.common.data.model.RawHandOut;
import com.penghaisoft.microwms.common.data.model.RawHandOutSn;
import com.penghaisoft.microwms.common.dto.HandResp;
import com.penghaisoft.microwms.common.dto.RawHandworkOutDto;
import com.penghaisoft.microwms.common.dto.RawOrderOutDto;
import com.penghaisoft.microwms.common.dto.Resp;
import com.penghaisoft.microwms.common.wms.model.RawCountingTask;
import com.penghaisoft.microwms.common.wms.model.RawStorageSn;
import com.penghaisoft.microwms.materialhand.web.outwarehouse.service.IMaterialHandOutWhService;
import com.penghaisoft.microwms.materialhand.web.outwarehouse.service.RawOrderOutService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/** 
* @ClassName: RawHandworkOutController 
* @Description: 手工出库
* @author jzh
* @date 2018年6月4日 上午10:30:40  
*/
@RestController
@RequestMapping(value = "raw/handworkout")
@Slf4j
public class RawHandworkOutController {

    @Autowired
    private IMaterialHandOutWhService iMaterialHandOutWhService;
   
    /** 
    * @Title: queryHandworkOut 
    * @Description: 手工出库 提单
    * @param @param rawOrderOutDto
    * @param @return  参数说明 
    * @return HandResp    返回类型
    * @author jzh 
    * @throws 
    */
    @PostMapping("queryhandworkout")
    public HandResp queryHandworkOut(@RequestBody RawHandworkOutDto rawHandworkOutDto){
        HandResp result = new HandResp();
        //Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        result.setMsg("手工出库单存在");
        if (rawHandworkOutDto.getHandOutNo()==null||rawHandworkOutDto.getHandOutNo().equals("")){
            result.setCode(Constant.FAIL);
            result.setMsg("请输入手工出库单号！");
            return result;
        }
        //设置查询标志（CountingCode=？ ，ActiveFlag = 1）
        RawHandOut rawHandOut = new RawHandOut();
        
        rawHandOut.setHandOutNo(rawHandworkOutDto.getHandOutNo());
        rawHandOut.setActiveFlag("1");
       
        List<RawHandOut> tmp = iMaterialHandOutWhService.queryHandworkOut(rawHandOut);
        if(tmp.size() > 0){
        	Boolean flag_all_2 = true;
    		for (RawHandOut handwork : tmp){
    			if(!"2".equals(handwork.getHandOutStatus())){
					flag_all_2 = false;
				}
    		}
    		if(flag_all_2){
    			result.setCode(Constant.FAIL);
            	result.setMsg("手工出库单全部发货完成！");
    		}
        }else{
        	result.setCode(Constant.FAIL);
        	result.setMsg("手工出库单不存在！");
        }
        return result;
    }

    /** 
    * @Title: queryHandOutDetail 
    * @Description: 根据手工出库单号查询详细信息
    * @param @param rawHandworkOutDto
    * @param @return  参数说明 
    * @return HandResp    返回类型
    * @author jzh 
    * @throws 
    */
    @PostMapping("queryhandoutdetail")
    public HandResp queryHandOutDetail(@RequestBody RawHandworkOutDto rawHandworkOutDto){
        HandResp result = new HandResp();
        //Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        if (rawHandworkOutDto.getHandOutNo()==null||rawHandworkOutDto.getHandOutNo().equals("")){
            result.setCode(Constant.FAIL);
            result.setMsg("请输入手工出库单号！");
            return result;
        }
        //设置查询标志（HandOutNo=？ ，ActiveFlag = 1）
        RawHandOut rawHandOut = new RawHandOut();
        
        rawHandOut.setHandOutNo(rawHandworkOutDto.getHandOutNo());
        rawHandOut.setActiveFlag("1");
       
        List<RawHandOut> tmp = iMaterialHandOutWhService.queryHandworkOutNot2(rawHandOut);
        if(tmp.size() > 0){
        	result.setList(tmp);
        	result.setMsg("成功查询出库单信息");
        	
        }else{
        	result.setCode(Constant.FAIL);
        	result.setMsg("手工出库单不存在！");
        }
        
        return result;
    }

    /** 
    * @Title: queryHandOutScan 
    * @Description: 扫描手工出库 
    * @param @param rawHandworkOutDto
    * @param (入参条码barcode，loginName，出库单号handOutNo)
    * @author jzh 
    */
    @PostMapping("queryhandoutscan")
    public HandResp queryHandOutScan(@RequestBody RawHandworkOutDto rawHandworkOutDto){
        HandResp result = new HandResp();
        //入参条码barcode，loginName，出库单号handOutNo
        String loginName = rawHandworkOutDto.getLoginName();
        String barcode = rawHandworkOutDto.getBarcode();
        String handOutNo = rawHandworkOutDto.getHandOutNo();
        Date now = new Date();
        
        RawStorageSn rawStorageSn = new RawStorageSn();
        rawStorageSn.setBarcode(barcode);
        //查询状态为可用0，非冻结1出库2
        rawStorageSn.setBarcodeStatus("0");
        rawStorageSn.setActiveFlag("1");
        List<RawStorageSn> list = iMaterialHandOutWhService.queryRawStorageSn(rawStorageSn);
        if(list.size()>0){
        	//找到该条码对应的型号,长度
        	String model = list.get(0).getModel();
        	BigDecimal amount = list.get(0).getAmount();
        	//出库单中对应型号
        	//设置查询标志（HandOutNo=？ ，ActiveFlag = 1,model）
            RawHandOut rawHandOut = new RawHandOut();
            rawHandOut.setHandOutNo(handOutNo);
            rawHandOut.setModel(model);
            rawHandOut.setActiveFlag("1");
            //根据出库单号，型号查询HandOut表
        	List<RawHandOut> tmp = iMaterialHandOutWhService.queryHandworkOutNot2(rawHandOut);
        	if(tmp.size()>0){
        		//需求数量
        		BigDecimal requireAmount = tmp.get(0).getRequireAmount()==null ? BigDecimal.ZERO : tmp.get(0).getRequireAmount();
        		//已分配数量
        		BigDecimal realAmount = tmp.get(0).getRealAmount()==null ? BigDecimal.ZERO : tmp.get(0).getRealAmount();
        		
		        BigDecimal val = (realAmount.add(amount)).subtract(requireAmount);
		        int b = val.compareTo(Constant.RAW_MAX_STATIC_METER);
		        
		        Boolean typeFlag = Constant.MODEL_L.equals(list.get(0).getModelType()) || 
		        		Constant.MODEL_W.equals(list.get(0).getModelType()) || Constant.MODEL_Z.equals(list.get(0).getModelType())
                        || Constant.MODEL_LDXG.equals(list.get(0).getModelType()) || Constant.MODEL_PE.equals(list.get(0).getModelType());
		        
        		//新分配数量=当前分配数量+条码对应型号的长度
        		BigDecimal newRealAmount = realAmount.add(amount);
        		
        		if (realAmount.compareTo(requireAmount) == 0 || requireAmount.compareTo(realAmount) < 0) {
					result.setCode(Constant.FAIL);
					result.setMsg("该型号已经扫码完成，无需继续扫码!");
					return result;
				}else if (typeFlag && b > 0) {
					result.setCode(Constant.FAIL);
					result.setMsg("该物料长度过长(实发数量只允许最多超过需求数量" + Constant.RAW_MAX_STATIC_METER + "米)!");
					return result;
				}else {
        		
            		Resp resp = new Resp();

            		//修改rawHandOut更改已分配数量为新数量
            		rawHandOut.setRealAmount(newRealAmount);
            		rawHandOut.setLastModifiedBy(loginName);
            		rawHandOut.setGmtModified(new Date());
            		rawHandOut.setHandOutId(tmp.get(0).getHandOutId());
            		
            		//新增记录RawHandOutSn实体
            		RawHandOutSn rawHandOutSn = new RawHandOutSn();
            		rawHandOutSn.setHandOutNo(handOutNo);
            		rawHandOutSn.setHandOutId(tmp.get(0).getHandOutId());
            		rawHandOutSn.setPurchaseNo(tmp.get(0).getPurchaseNo());
            		rawHandOutSn.setContractNo(tmp.get(0).getContractNo());
            		rawHandOutSn.setBarcode(barcode);
            		rawHandOutSn.setModel(model);
            		rawHandOutSn.setModelDesc(tmp.get(0).getModelDesc());
            		rawHandOutSn.setModelType(tmp.get(0).getModelType());
            		rawHandOutSn.setType(tmp.get(0).getType());
            		rawHandOutSn.setAmount(amount);
            		rawHandOutSn.setUnit(tmp.get(0).getUnit());
            		rawHandOutSn.setWhCode(list.get(0).getWhCode());
            		rawHandOutSn.setWdCode(list.get(0).getWdCode());
            		rawHandOutSn.setWaCode(list.get(0).getWaCode());
            		rawHandOutSn.setScanStatus("0");
            		rawHandOutSn.setCreateBy(loginName);
            		rawHandOutSn.setGmtCreate(now);
            		rawHandOutSn.setActiveFlag("1");
            		
            		//更改条码状态为已出库
        			RawStorageSn rawStorageSnNew = new RawStorageSn();
//        			rawStorageSnNew.setActiveFlag("1");
        			rawStorageSnNew.setStorageSnId(list.get(0).getStorageSnId());
        			rawStorageSnNew.setBarcodeStatus("2");
        			rawStorageSnNew.setLastModifiedBy(loginName);
        			rawStorageSnNew.setGmtModified(now);
            
            		try{
            		//更改已分配数量为新数量 并且 新增记录,更改条码状态为已出库（保证事物）
            		resp = iMaterialHandOutWhService.updateAndCreateHandOut(rawHandOut,rawHandOutSn,rawStorageSnNew);
            		}catch(RuntimeException e){
            			result.setCode("0");
            			System.out.print(e.getMessage());
            			result.setMsg(e.getMessage());
            			return result;
            		}
            		//成功
            		result.setCode(resp.getCode());
        			result.setList(list);
               
        		}
        	}else{
        		result.setCode(Constant.FAIL);
            	result.setMsg("此条码与该手工入库单不对应");
        	}
        
        }else{
        	result.setCode(Constant.FAIL);
        	result.setMsg("此条码不存在或已出库冻结");
        }

        return result;
    }
    
    
    /** 
    * @Title: handworkBack 
    * @Description: 退扫
    * @param @param rawHandworkOutDto
    * @param @return  参数说明 
    * @return HandResp    返回类型
    * @author jzh 
    * @throws 
    */
    @PostMapping("handworkback")
    public HandResp handworkBack(@RequestBody RawHandworkOutDto rawHandworkOutDto){
        HandResp result = new HandResp();
        //Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        //入参条码barcode，loginName，出库单号handOutNo,型号model,数量amount
        String loginName = rawHandworkOutDto.getLoginName();
        String barcode = rawHandworkOutDto.getBarcode();
        String handOutNo = rawHandworkOutDto.getHandOutNo();
        String model = rawHandworkOutDto.getModel();
        BigDecimal amount = rawHandworkOutDto.getAmount();
        Resp resp = new Resp();
        //将RawHandOutSn的scan_status置为退扫
        RawHandOutSn rawHandOutSn = new RawHandOutSn();
        rawHandOutSn.setHandOutNo(handOutNo);
        rawHandOutSn.setModel(model);
        rawHandOutSn.setBarcode(barcode);
//        rawHandOutSn.setScanStatus("1");//1退扫
//        退扫改用activeflag
        rawHandOutSn.setActiveFlag("0");
        //将rawHandOut实发数量-数量
        RawHandOut rawHandOut = new RawHandOut();
        rawHandOut.setHandOutNo(handOutNo);
        rawHandOut.setModel(model);
        List<RawHandOut> tmp = iMaterialHandOutWhService.queryHandworkOut(rawHandOut);
        BigDecimal newRealAmount = tmp.get(0).getRealAmount().subtract(amount);
        rawHandOut.setRealAmount(newRealAmount);
        rawHandOut.setHandOutId(tmp.get(0).getHandOutId());
        //将rawStorageSn的BarcodeStatus置为0可用
        RawStorageSn rawStorageSn  = new RawStorageSn();
        rawStorageSn.setBarcode(barcode);
        rawStorageSn.setBarcodeStatus("0");
        
		try{
    		//将RawHandOutSn的scan_status置为退扫，将rawHandOut实发数量-数量，
			//将rawStorageSn的BarcodeStatus置为0可用（保证事物）
    		resp = iMaterialHandOutWhService.handworkBack(rawHandOutSn,rawHandOut,rawStorageSn);
    		}catch(RuntimeException e){
    			result.setCode("0");
    			System.out.print(e.getMessage());
    			result.setMsg(e.getMessage());
    			return result;
    		}
		result.setMsg("退扫成功");
        
        return result;
    }
    
    
    @PostMapping("handworkconfig")
    public HandResp handworkConfig(@RequestBody RawHandworkOutDto rawHandworkOutDto){
        HandResp result = new HandResp();
        //Code先置为1SUCCESS
        result.setCode(Constant.SUCCESS);
        //入参条码barcode，loginName，出库单号handOutNo,型号model,数量amount
        String loginName = rawHandworkOutDto.getLoginName();
        String handOutNo = rawHandworkOutDto.getHandOutNo();
			
        //设置查询标志（HandOutNo=？ ，ActiveFlag = 1）
        RawHandOut rawHandOut = new RawHandOut();
        
        rawHandOut.setHandOutNo(handOutNo);
        rawHandOut.setActiveFlag("1");
       
        List<RawHandOut> tmp = iMaterialHandOutWhService.queryHandworkOutNot2(rawHandOut);
        for(RawHandOut handWork : tmp){
        	//已扫数量小于需求数量
        	//if(handWork.getRealAmount().compareTo(handWork.getRequireAmount())==0||handWork.getRealAmount().compareTo(handWork.getRequireAmount())==1){
    		if(handWork.getRealAmount().compareTo(handWork.getRequireAmount())==-1){
    			String model = handWork.getModel();
        		result.setCode("0");
        		result.setMsg("该出库单下型号"+model+"未扫描完");
        		return result;
        	}
        }
        //将出库单置为已发货2
        Resp resp = new Resp();
        rawHandOut.setLastModifiedBy(loginName);
        rawHandOut.setGmtModified(new Date());
        rawHandOut.setHandOutStatus("2");
        resp = iMaterialHandOutWhService.updateHandwork(rawHandOut);
        result.setCode(resp.getCode());
        if(resp.getMsg()!= null){
        	result.setMsg(resp.getMsg());
        }else{
        	result.setMsg("发货成功");
        }
        return result;
    }

}
